package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.*;
import cn.wolfcode.crm.service.IHangSaleBillService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class HangSaleBillService implements IHangSaleBillService {

    @Autowired
    private HangSaleBillMapper hangSaleBillMapper;
    @Autowired
    private HangSaleBillItemMapper hangSaleBillItemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private SaleOutMapper saleOutMapper;
    @Autowired
    private SaleOutItemMapper saleOutItemMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private RechargeItemMapper rechargeItemMapper;
    @Autowired
    private IntegralItemMapper integralItemMapper;

    public void deleteByPrimaryKey(Long id) {
        //删除挂单明细
        hangSaleBillItemMapper.deleteByBillId(id);
        //删除挂单
        hangSaleBillMapper.deleteByPrimaryKey(id);
    }

    public HangSaleBill selectByPrimaryKey(Long id) {
        return hangSaleBillMapper.selectByPrimaryKey(id);
    }

    public List<HangSaleBill> selectAll() {
        return hangSaleBillMapper.selectAll();
    }

    public int updateByPrimaryKey(HangSaleBill record) {
        return hangSaleBillMapper.updateByPrimaryKey(record);
    }

    public void save(HangSaleBill hangSaleBill) {
        /*保存单据*/
        //设置sn
        hangSaleBill.setSn(String.valueOf(new Date().getTime()).substring(4));
        //总数量和总价
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //迭代明细
        for (HangSaleBillItem item : hangSaleBill.getItems()) {
            BigDecimal salePrice = item.getSalePrice();
            BigDecimal number = item.getNumber();
            BigDecimal amount = salePrice.multiply(number).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //计算单据的total
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(number);
        }
        //设置单据的total
        hangSaleBill.setTotalAmount(totalAmount);
        hangSaleBill.setTotalNumber(totalNumber);
        hangSaleBillMapper.insert(hangSaleBill);
        /*保存明细*/
        for (HangSaleBillItem item : hangSaleBill.getItems()) {
            item.setBillId(hangSaleBill.getId());
            hangSaleBillItemMapper.insert(item);
        }
    }

    /*付款*/
    public void payment(SaleOut saleOut) {
        //判断库存是否足够
        for (SaleOutItem item : saleOut.getItems()) {
            Product product = productMapper.selectByPrimaryKey(item.getProduct().getId());
            ProductStock productStock = productStockMapper.selectByPrimaryKey(item.getProduct().getId(), saleOut.getDepot().getId());
            if (productStock == null) {
                throw new RuntimeException("库存中没有["+product.getName()+"]商品");
            }
            if(item.getNumber().compareTo(productStock.getStoreNumber())==1){
                throw new RuntimeException("商品["+product.getName()+"]库存不足");
            }
        }

        //销售单据和明细保存
        //单据值的设置
        saleOut.setSn(String.valueOf(new Date().getTime()).substring(4,7));
        saleOut.setVdate(new Date());
        saleOut.setStatus(2);
        saleOut.setAuditTime(new Date());
        saleOut.setInputTime(new Date());
        saleOut.setInputUser(UserContext.getCurrentUser());
        saleOut.setAuditor(UserContext.getCurrentUser());
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //明细值设置
        for (SaleOutItem item : saleOut.getItems()) {
            //计算明细中的小计
            BigDecimal salePrice = item.getSalePrice();
            BigDecimal number = item.getNumber();
            BigDecimal amount = salePrice.multiply(number).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //计算所有明细的总量和总价
            totalAmount = totalAmount.add(item.getAmount());
            totalNumber = totalNumber.add(item.getNumber());
        }
        //保存单据
        saleOut.setTotalNumber(totalNumber);
        saleOut.setTotalAmount(totalAmount);
        saleOutMapper.insert(saleOut);
        //保存明细
        for (SaleOutItem item : saleOut.getItems()) {
            item.setOutId(saleOut.getId());
            saleOutItemMapper.insert(item);
        }

        //会员的积分增加
        Client client = clientMapper.selectByPrimaryKey(saleOut.getClient().getId());
        Integer integral = client.getIntegral();
        Integer changeIntegral = 0;
        for (SaleOutItem item : saleOut.getItems()) {
            Product product = productMapper.selectByPrimaryKey(item.getProduct().getId());
            integral += product.getIntegral();
            changeIntegral += product.getIntegral();
        }
        client.setIntegral(integral);
        clientMapper.updateByPrimaryKey(client);
        //会员个人消费记录
        RechargeItem rechargeItem = new RechargeItem();
        rechargeItem.setOperation(0);
        rechargeItem.setOptime(new Date());
        rechargeItem.setBeforeBalance(client.getBalance());
        rechargeItem.setAddincome(new BigDecimal(0));
        rechargeItem.setIncome(saleOut.getTotalAmount());
        rechargeItem.setOpUser(UserContext.getCurrentUser());
        BigDecimal afterBalance = client.getBalance().subtract(saleOut.getTotalAmount());
        rechargeItem.setAfterBalance(afterBalance);
        rechargeItem.setClient(saleOut.getClient());
        rechargeItemMapper.insert(rechargeItem);

        //减少库存
        //获取仓库的商品
        for (SaleOutItem item : saleOut.getItems()) {
            ProductStock productStock = productStockMapper.selectByProductAndDepot(item.getProduct().getId(), saleOut.getDepot().getId());
            BigDecimal subtract = productStock.getStoreNumber().subtract(item.getNumber());
            productStock.setStoreNumber(subtract);
            BigDecimal amount = productStock.getAmount().subtract(item.getAmount());
            productStock.setAmount(amount);
            productStockMapper.updateByPrimaryKey(productStock);
        }
        //积分记录
        IntegralItem integralItem = new IntegralItem();
        integralItem.setChangeIntegral(changeIntegral);
        integralItem.setOperation(2);
        integralItem.setClient(saleOut.getClient());
        integralItemMapper.insert(integralItem);
    }
}
